function getColor() {
  return '#' + (Math.random() * 0xFFFFFF << 0).toString(16);
}

export function createText(ctor, char, {fontSize}) {
  return new ctor(char, fontSize + " Georgia", getColor());
}
export function setPosition(text, x, y) {
  text.x = x;
  text.y = y;
}

// 随机生成小写字母
export function randomGen() {
  var charCode = 97 + Math.round(Math.random() * 25);
  return String.fromCharCode(charCode);
}

// 按照指定范围生成字母
export function letterGenerator( charRange ){
  var len = charRange.length;
  return function(){
    var index = Math.floor(Math.random() * len);
    return charRange[index];
  }
}

// 随机大小写
export const randomCase = ( char )=>{
  if( Math.random() > 0.5 ){
    return char.toLowerCase();
  }
  return char.toUpperCase();
};

function speaker(src, cb) {
  var audio = document.createElement('audio');
  audio.autoplay = true;
  if( typeof cb === 'function' ){
    audio.onended = cb;
  }
  audio.src = src;
}

export const say = (src, repeat) => {
  if (repeat > 0) {
    speaker( src, ()=>{
      say(src, --repeat);
    }); // 重复读
  }
}

// 过滤非字母字符
export const filterCharacter = (range) => {
  return range.filter(char => {
    return /^[a-z,A-Z]$/.test(char);
  });
}

export const uniqueArr = ( arr )=>{
  return Array.from(new Set(arr));
}

const IteratorToObject = ( it )=>{
  const keys = it.keys();
  const ret = Object.create(null);
  for(let key of keys){
    ret[key] = it.get(key);
  }
  return ret;
};

const getHashParams = ( hash ) => {
  if( hash && hash.length > 2 ){
    hash = hash.slice(1);
  }
  const params = new URLSearchParams( hash );
  return IteratorToObject( params );
};

export const getUrlParams = ()=>{
  const {
    hash,
    search,
  } = window.location;
  if( hash ) {
    return getHashParams(hash);
  }
  else{
    return getHashParams(search);// 兼容 search
  }
};